﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UniUI.ConsoleUI
{
    public class ConsoleFieldCtrl : IConsoleFocusControl
    {
        public ConsoleFieldCtrl(IConsoleControl parent, int labelWidth, int textWidth)
        {
            this.ParentControl = parent;

            this.LabelGrid = new ConsoleGrid(this, false);
            this.LabelGrid.Width = labelWidth;

            this.EditGrid = new ConsoleGrid(this, true);
            this.EditGrid.Left = labelWidth;
            this.EditGrid.Width = textWidth;
        }

        public ConsoleGrid LabelGrid { get; private set; }
        public ConsoleGrid EditGrid { get; private set; }

        public int CursorX
        {
            get { return EditGrid.CursorX; }
        }

        public int CursorY
        {
            get { return EditGrid.CursorY; }
        }

        public bool ShowCursor
        {
            get { return EditGrid.ShowCursor; }
        }

        public void GetFocus()
        {
            EditGrid.GetFocus();
        }

        public void LostFocus()
        {
            EditGrid.LostFocus();
        }

        public bool CanGetFocus
        {
            get { return EditGrid.CanGetFocus; }
        }

        public void OnKeyPress(ConsoleKeyInfo key, bool isInsertMode)
        {
            EditGrid.OnKeyPress(key, isInsertMode);
        }

        public IConsoleControl ParentControl { get; private set; }

        private int _Left;
        public int Left
        {
            get { return _Left; }
            set
            {
                this.InvalidateParent();
                _Left = value;
            }
        }

        private int _Top;
        public int Top
        {
            get { return _Top; }
            set
            {
                this.InvalidateParent();
                _Top = value;
            }
        }

        public int Width { get { return LabelGrid.Width + EditGrid.Width; } }
        public int Height { get { return 1; } }

        public void Render(ConsoleScreen screen)
        {
            if (dirty)
            {
                LabelGrid.Render(screen);
                EditGrid.Render(screen);
            }
        }

        private bool dirty = true;

        public void Invalidate(int left, int top, int width, int height)
        {
            dirty = true;

            LabelGrid.Invalidate();
            EditGrid.Invalidate();
        }
    }
}
